﻿using DotNetHackathon.GBA.ApiCommon.ExceptionHandling;
using DotNetHackathon.GBA.ApiCommon.JsonSerializing;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace DotNetHackathon.GBA.ApiCommon
{
    public static class ApiCommonExtensions
    {
        public static IServiceCollection AddApiCommonServices(this IServiceCollection services)
        {
            services.AddSingleton<IJsonSerializer, DefaultJsonSerializer>()
                .AddSingleton<IExceptionToErrorResultConverter, DefaultExceptionToErrorResultConverter>()
                .AddSingleton<IHttpExceptionStatusCodeFinder, DefaultHttpExceptionStatusCodeFinder>()
                .AddSingleton<IExceptionToResponseTextConverter, DefaultExceptionToResponseTextConverter>();

            return services;
        }
        public static async Task HandleAndWrapException(HttpContext httpContext, Exception exception)
        {
            var statusCodeFinder = httpContext.RequestServices.GetRequiredService<IHttpExceptionStatusCodeFinder>();
            var responseTextConverter = httpContext.RequestServices.GetRequiredService<IExceptionToResponseTextConverter>();

            httpContext.Response.StatusCode = (int)statusCodeFinder.GetStatusCode(httpContext, exception);
            await httpContext.Response.WriteAsync(
                responseTextConverter.Convert(exception)
                );
        }
    }
}
